//
// Created by pulsarv on 19-5-2.
//

#include <asio/rc_socket_server.h>
#include <iostream>

rc_socket_server::rc_socket_server(QObject *parent) {

}


void rc_socket_server::set_server_properties(int port, int max_buffer_size) {

}

rc_socket_server::rc_socket_server(int port, int max_buffer_size,QObject *parent) :QTcpServer(parent), port(port), max_buffer_size(max_buffer_size) {
    this->tcp_server = new QTcpServer();

}


rc_socket_server::~rc_socket_server() {
    this->tcp_server->close();
    this->tcp_server->deleteLater();
}

void rc_socket_server::bind_call(void (*bind_function)(void *)) {
    this->bind_function = bind_function;
}

void rc_socket_server::start_listen() {
    std::cout << "Start Listen On:"<<this->port << std::endl;
    this->tcp_server->listen(QHostAddress::LocalHost, this->port);
    connect(this->tcp_server, &QTcpServer::newConnection, this, &rc_socket_server::server_new_connection);
}

void rc_socket_server::server_new_connection() {

    std::cout << "New User" << std::endl;
    this->tcp_socket = this->tcp_server->nextPendingConnection();
    if (!this->tcp_socket) {
        return;
    } else {
        connect(tcp_socket, SIGNAL(readyRead()), this, SLOT(server_read_data()));
        connect(tcp_socket, SIGNAL(disconnected()), this, SLOT(server_disconnect()));
    }
}

void rc_socket_server::server_read_data() {
    char *buffer = new char[this->max_buffer_size];
    this->tcp_socket->read(buffer, this->max_buffer_size);
    if (strlen(buffer) > 0) {
        std::string message = buffer;
//        this->bind_function((void*)(&message));
    } else {
        return;
    }
}

void rc_socket_server::server_disconnect() {
    return;
}
